/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.attachment.controller  
 */
package com.apache.attachment.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.apache.action.PlatFromAction;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.LoggerVo;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.attachment.entity.AttachmentRegister;
import com.apache.attachment.entity.AttachmentStore;
import com.apache.attachment.manager.AttachmentRegisterManager;
import com.apache.attachment.manager.AttachmentStoreManager;
import com.apache.attachment.mommon.AttachmentConfig;
import com.apache.attachment.mommon.FileUtil;
import com.apache.attachment.mommon.ImageUtil;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.passport.common.PassportHelper;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;

/**
 * description:  
 * @author mhguo 创建时间：2015-5-26  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
@Controller
@RequestMapping("/attachment/files/")
public class AttachmentFilesAction extends PlatFromAction {

	/**
	 * 附件信息管理的Service
	 */
	@Autowired
	AttachmentStoreManager attachmentStoreManager;

	/**
	 * 附件库注册管理的Service
	 */
	@Autowired
	AttachmentRegisterManager attachmentRegisterManager;

	/**
	 *上传附件，修改图片信息 
	 */
	@RequestMapping("uploadAttachment.action")
	public @ResponseBody
	Object uploadAttachment(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, String id)
			throws BusinessException {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		//参数检查
		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示

		if (Validator.isNull(objId) || Validator.isNull(objType)) {
			return getResultMsg(request, "缺少必要的参数，系统调用异常!");
		}

		//实体注册信息检查
		AttachmentRegister ar = new AttachmentRegister();
		ar.setRegEname(objType);
		ParamsVo vo = new ParamsVo();
		vo.setObj(ar);
		List<AttachmentRegister> arList = attachmentRegisterManager.getList(vo);

		if (arList.size() < 1) {
			return getResultMsg(request, "实体未注册!");
		} else {
			AttachmentRegister r = arList.get(0);//注册信息

			LoggerVo loggerVo = new LoggerVo();
			ParamsVo<AttachmentStore> voStore = this.getParamsVo(request);

			if (Validator.isNull(id)) {//新增

				int attTotal = 0;
				int attListTotal = 0;
				attTotal = r.getPicTotalNum();//最大上传个数

				if (Validator.isEmpty(file)) {
					return getResultMsg(request, "请选择要上传的附件!");
				}

				String fileFileName = file.getOriginalFilename();
				String nameEx = FileUtil.getInstance().getExtension(fileFileName);//取得文件扩展名
				//附件类型校验
				String alt = StrUtil.doNull(r.getAlloweTypes()).toUpperCase();
				if (!alt.equals("*.*")) {
					if (StrUtil.isNotEmptyWithTrim(alt) && alt.indexOf(nameEx.toUpperCase()) == -1) {
						return getResultMsg(request, "不允许的文件类型!");
					}
				}

				//根据objType和objId获得附件信息集合
				AttachmentStore as = new AttachmentStore();
				as.setObjType(objType);
				as.setObjId(objId);
				vo.setObj(as);
				List<AttachmentStore> asList = attachmentStoreManager.getList(vo);
				attListTotal = asList.size();

				if (attTotal <= attListTotal && attTotal > 0) {//验证附件数量
					//vinSwfUpload插件所需参数：flag,message,fileState(0:上传错误；1：上传成功)
					Map<String, Object> mapData = new HashMap<String, Object>();
					mapData.put("flag", "false");
					mapData.put("message", "您上传的附件已经超过预定设置上传个数:(" + attTotal + "个)!");
					mapData.put("fileState", "0");
					return mapData;
				} else if (attTotal < 0) {
					//return getResultMsg(request, "预定设置上传个数不能为负数!");
					Map<String, Object> mapData = new HashMap<String, Object>();
					mapData.put("flag", "false");
					mapData.put("message", "预定设置上传个数不能为负数!");
					mapData.put("fileState", "0");
					return mapData;
				}

				if (file.getSize() / 1024L > r.getMaxLength()) {//验证附件大小
					//return getResultMsg(request, "你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
					Map<String, Object> mapData = new HashMap<String, Object>();
					mapData.put("flag", "false");
					mapData.put("message", "你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
					mapData.put("fileState", "0");
					return mapData;
				}

				/*	if (file.getSize() / 1024L < 10) {//验证附件大小
						//return getResultMsg(request, "你的附件小于10KB,请处理后重新上传!");
						Map<String, Object> mapData = new HashMap<String, Object>();
						mapData.put("flag", "false");
						mapData.put("message", "你的附件小于10KB,请处理后重新上传!");
						mapData.put("fileState", "0");
						return mapData;
					}*/

				String fileContentType = file.getContentType();
				logger.info(file.getName() + "  " + fileFileName + "  " + fileContentType);

				String uploadPath;//附件上传目录前段
				String downloadUrl;//附件下载地址前段

				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {//图片
					uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/pics/";
					downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL") + "/pics/";
				} else {//文件
					uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/atta/";
					downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL") + "/atta/";
				}

				if (StrUtil.isEmptyWithTrim(uploadPath)) {
					uploadPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
				}

				//附件上传、下载目录的后段
				String cacDir = "/" + objType + "/" + new SimpleDateFormat("yyyyMM").format(new Date()) + "/" + objId
						+ "/";
				String uplDir = uploadPath + cacDir;
				File s = new File(uplDir);
				if (!s.exists()) {
					FileUtil.getInstance().makDir(uplDir);//如果上传目录不存在，则创建
				}

				String AttachmentId = String.valueOf(System.currentTimeMillis());
				String wrFileName = cacDir + AttachmentId + "." + nameEx;
				logger.info("-----------最终文件名：" + wrFileName);
				String wrMiddleFileName = "";
				String wrSmallFileName = "";

				//图片上传会产生3张图：原图、中图、小图
				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {
					wrMiddleFileName = cacDir + AttachmentId + ".m." + nameEx;
					logger.info("wrMiddleFileName[{}]" + wrMiddleFileName);
					wrSmallFileName = cacDir + AttachmentId + ".s." + nameEx;
					logger.info("wrSmallFileName[{}]" + wrSmallFileName);

					try {
						FileUtil.getInstance().writeFile(file, uploadPath + wrFileName);
						logger.info("-----------原图上传成功：" + wrFileName);
						FileUtil.getInstance().copy(new File(uploadPath + wrFileName),
								new File(uploadPath + wrSmallFileName));
						logger.info("-----------小图创建成功：" + wrSmallFileName);
						ImageUtil.getInstance().resize(uploadPath + wrSmallFileName,
								(r.getSmallWidth() == null) ? 0 : r.getSmallWidth(),
								(r.getSmallHeight() == null) ? 0 : r.getSmallHeight());
						logger.info("-----------小图缩放成功：" + wrFileName);
						FileUtil.getInstance().copy(new File(uploadPath + wrFileName),
								new File(uploadPath + wrMiddleFileName));
						logger.info("-----------中图创建成功：" + wrMiddleFileName);
						ImageUtil.getInstance().resize(uploadPath + wrMiddleFileName,
								(r.getMiddleWidth() == null) ? 0 : r.getMiddleWidth(),
								(r.getMiddleHeigth() == null) ? 0 : r.getMiddleHeigth());
						logger.info("-----------中图缩放成功：" + wrFileName);
						String wmf = StrUtil.doNull(r.getWatermarkFile());
						if (StrUtil.isNotEmptyWithTrim(wmf)) {
							ImageUtil.getInstance().pressImage(r.getWatermarkFile(), uploadPath + wrMiddleFileName,
									r.getWmX(), r.getWmY(), r.getWmFilter().floatValue());
							logger.info("-----------中图添加水印成功：" + wrFileName);
						}
					} catch (FileNotFoundException e) {
						logger.error(">>>>>>>>>图片未找到，上传失败!!!!!!" + e);
						return getResultMsg(request, "图片未找到，上传失败!");
					} catch (IOException e) {
						logger.error(">>>>>>>>>图片操作异常!!!!!!!!" + e);
						return getResultMsg(request, "图片操作异常!");
					}
				} else {
					try {
						FileUtil.getInstance().writeFile(file, uploadPath + wrFileName);
						logger.info("-----------附件原图上传成功：" + wrFileName);
					} catch (FileNotFoundException e) {
						logger.error(">>>>>>>>>附件未找到，上传失败!!!!!!" + e);
						return getResultMsg(request, "附件未找到，上传失败!");
					} catch (IOException e) {
						logger.error(">>>>>>>>>附件操作异常!!!!!!!!" + e);
						return getResultMsg(request, "附件操作异常!");
					}
				}

				AttachmentStore attaStore = new AttachmentStore();
				String fileName = getFileName(fileFileName);
				attaStore.setSid(AttachmentId);
				attaStore.setObjId(objId);
				attaStore.setObjType(objType);//实体注册类型(注册英文标示)
				attaStore.setAttachmentDesc(fileName);
				attaStore.setAttachmentName(fileName);
				attaStore.setDownloadUrl(downloadUrl + cacDir);//下载地址(不包括文件名)
				attaStore.setAbsolutePath(uploadPath + cacDir);//附件绝对路径(不包括文件名)
				attaStore.setAttachmentType(nameEx);//附件类型(附件扩展名)
				String mainPicFlag = request.getParameter("mainPicFlag");
				if (Validator.isNotNull(mainPicFlag))
					attaStore.setMainPicFlag(mainPicFlag);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
				attaStore.setCreateTime(sdf.format(new Date()));
				//集成单点登录后，获得登录用户信息的方式
				String tokenId = PassportHelper.getInstance().getCurrCookie(request);

				//session中已经存在用户登录对象，则从session中获取
				Object loginObj = request.getSession().getAttribute("loginUser");
				LoginUser loginUser = null;
				if (loginObj == null) {
					loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(tokenId);
				} else {
					loginUser = PBOSSOTools.getLoginUser(request);
				}
				if (loginUser == null) {
					this.logger.info("AttachmentFilesAction(uploadAttachment方法)中未获取到loginUser登录信息:" + loginUser);
				}

				if (null != loginUser) {
					attaStore.setCreateUserId(loginUser.getUserId());
					attaStore.setCreateUserRealname(loginUser.getUserCname());
					attaStore.setCreateSpaceEname(loginUser.getUserEname());
					attaStore.setServerid(loginUser.getDataDomain());
				} else {
					String createUserId = request.getParameter("createUserId");
					String createUserRealname = request.getParameter("createUserRealname");
					String createSpaceEname = request.getParameter("createSpaceEname");
					if (Validator.isNotNull(createUserId))
						attaStore.setCreateUserId(createUserId);
					if (Validator.isNotNull(createUserRealname))
						attaStore.setCreateUserId(createUserRealname);
					if (Validator.isNotNull(createSpaceEname))
						attaStore.setCreateUserId(createSpaceEname);
				}

				voStore.setObj(attaStore);
				String rsid = attachmentStoreManager.saveInfo(voStore);
				if (Validator.isNull(rsid)) {
					//return getResultMsg(request, "新增条目失败，请重试！");
					Map<String, Object> mapData = new HashMap<String, Object>();
					mapData.put("flag", "false");
					mapData.put("message", "新增条目失败，请重试！");
					mapData.put("fileState", "0");
					return mapData;
				}
				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {
					if (Validator.isNotNull(mainPicFlag) && "1".equals(mainPicFlag.trim()))
						setMainPicFlag(request, rsid);
				}
			} else {//修改
				ParamsVo voup = new ParamsVo();
				voup.setInfoId(id);
				AttachmentStore attaStoreEntity = (AttachmentStore) attachmentStoreManager.getInfoById(voup);

				//校验附件是否存在
				if (Validator.isEmpty(attaStoreEntity)) {
					return getResultMsg(request, "附件不存在或者已经删除！");
				}

				//替换附件
				if (!file.isEmpty()) {

					String fileFileName = file.getOriginalFilename();
					String nameEx = FileUtil.getInstance().getExtension(fileFileName);//取得文件扩展名
					//附件类型校验
					String alt = StrUtil.doNull(r.getAlloweTypes()).toUpperCase();
					if (!alt.equals("*.*")) {
						if (StrUtil.isNotEmptyWithTrim(alt) && alt.indexOf(nameEx.toUpperCase()) == -1) {
							return getResultMsg(request, "不允许的文件类型!");
						}
					}

					if (file.getSize() / 1024L > r.getMaxLength()) {
						return getResultMsg(request, "你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
					}

					/*if (file.getSize() / 1024L < 10) {
						return getResultMsg(request, "你的附件小于10KB,请处理后重新上传!");
					}*/

					String attafileName = attaStoreEntity.getSid() + "." + attaStoreEntity.getAttachmentType();
					String uploadDir = getUploadDir(request, id, attaStoreEntity);
					String uploadDirpro = uploadDir + attafileName;//原图上传地址

					if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {
						String wrMiddleFileName = attaStoreEntity.getSid() + ".m."
								+ attaStoreEntity.getAttachmentType();
						logger.info("wrMiddleFileName[{}]" + wrMiddleFileName);
						String uploadDirm = uploadDir + wrMiddleFileName;//中图上传地址
						String wrSmallFileName = attaStoreEntity.getSid() + ".s." + attaStoreEntity.getAttachmentType();
						logger.info("wrSmallFileName[{}]" + wrSmallFileName);
						String uploadDirs = uploadDir + wrSmallFileName;//小图上传地址
						try {
							FileUtil.getInstance().writeFile(file, uploadDirpro);
							logger.info("-----------原图上传成功：" + attafileName);
							FileUtil.getInstance().copy(new File(uploadDirpro), new File(uploadDirs));
							logger.info("-----------小图创建成功：" + wrSmallFileName);
							ImageUtil.getInstance().resize(uploadDirs,
									(r.getSmallWidth() == null) ? 0 : r.getSmallWidth(),
									(r.getSmallHeight() == null) ? 0 : r.getSmallHeight());
							logger.info("-----------小图缩放成功：" + attafileName);
							FileUtil.getInstance().copy(new File(uploadDirpro), new File(uploadDirm));
							logger.info("-----------中图创建成功：" + wrMiddleFileName);
							ImageUtil.getInstance().resize(uploadDirm,
									(r.getMiddleWidth() == null) ? 0 : r.getMiddleWidth(),
									(r.getMiddleHeigth() == null) ? 0 : r.getMiddleHeigth());
							logger.info("-----------中图缩放成功：" + attafileName);
							String wmf = StrUtil.doNull(r.getWatermarkFile());
							if (StrUtil.isNotEmptyWithTrim(wmf)) {
								ImageUtil.getInstance().pressImage(r.getWatermarkFile(), uploadDirm, r.getWmX(),
										r.getWmY(), r.getWmFilter().floatValue());
								logger.info("-----------中图添加水印成功：" + attafileName);
							}
						} catch (FileNotFoundException e) {
							logger.error(">>>>>>>>>原图未找到，上传失败!!!!!!" + e);
							return getResultMsg(request, "原图未找到，上传失败!");
						} catch (IOException e) {
							logger.error(">>>>>>>>>图片操作异常!!!!!!!!" + e);
							return getResultMsg(request, "图片操作异常!");
						}

					} else {
						try {
							FileUtil.getInstance().writeFile(file, uploadDir);
						} catch (FileNotFoundException e) {
							logger.error(">>>>>>>>>附件未找到，替换附件失败!!!!!!" + e);
							return getResultMsg(request, "附件未找到，替换附件失败!");
						} catch (IOException e) {
							logger.error(">>>>>>>>>附件操作异常!!!!!!!!" + e);
							return getResultMsg(request, "附件操作异常!");
						}
					}

				}

				String attachmentDesc = request.getParameter("attachmentDesc");
				String attachmentName = request.getParameter("attachmentName");
				String mainPicFlag = request.getParameter("mainPicFlag");
				if (Validator.isNotNull(attachmentDesc))
					attaStoreEntity.setAttachmentDesc(attachmentDesc);
				if (Validator.isNotNull(attachmentName))
					attaStoreEntity.setAttachmentName(attachmentName);
				if (Validator.isNotNull(mainPicFlag))
					attaStoreEntity.setMainPicFlag(mainPicFlag);

				//BeanUtils.copyProperties(attaStore, attaStoreEntity);
				voup.setInfoId(null);
				voup.setObj(attaStoreEntity);
				boolean mark = attachmentStoreManager.editInfo(voup);
				if (!mark) {
					rmsg.setFlag("F");
					rmsg.setMsg("操作失败！");
				}
				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {
					if (Validator.isNotNull(mainPicFlag) && "1".equals(mainPicFlag.trim()))
						setMainPicFlag(request, attaStoreEntity.getSid());
				}
			}
		}

		return rmsg;
	}

	/**
	 *上传附件，保存实体信息 
	 */
	@RequestMapping("uploadAttachmentFile.action")
	public ModelAndView uploadAttachmentFile(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) {
		ModelAndView view = new ModelAndView("attachment/mvc/attachment-upload-media");

		String sid = request.getParameter("sid");//
		String domain = AttachmentConfig.getProp("DOMAIN");//设置域
		String callback = request.getParameter("callback");//是否有回调函数
		String idname = request.getParameter("idname");
		String isRemote = request.getParameter("isRemote");//是否跨域
		view.addObject("callback", callback);//回调函数名
		view.addObject("idname", idname);//回显html元素的ID
		view.addObject("isRemote", isRemote);//是否跨域
		view.addObject("domain", domain);//域

		logger.info("domain=" + domain + "; callback=" + callback + "; idname=" + idname + "; isRemote=" + isRemote
				+ "; sid=" + sid);

		//参数检查
		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示

		if (Validator.isNull(objId) || Validator.isNull(objType)) {
			view.addObject("flag", "F");
			view.addObject("msg", "缺少必要的参数，系统调用异常!");
			logger.info("缺少必要的参数objId和objType!");
			return view;
		}

		//实体注册信息检查
		AttachmentRegister ar = new AttachmentRegister();
		ar.setRegEname(objType);
		ParamsVo vo = new ParamsVo();
		vo.setObj(ar);
		List<AttachmentRegister> arList = attachmentRegisterManager.getList(vo);

		if (arList.size() < 1) {
			view.addObject("flag", "F");
			view.addObject("msg", "服务端附件信息未注册!");
			logger.info("AttachmentRegister表中实体未注册!");
			return view;
		} else {
			AttachmentRegister r = arList.get(0);//注册信息

			LoggerVo loggerVo = new LoggerVo();
			ParamsVo<AttachmentStore> voStore = this.getParamsVo(request);

			logger.info("附件上传 start..........");
			int attTotal = 0;
			int attListTotal = 0;
			attTotal = r.getPicTotalNum();//最大上传个数

			if (Validator.isEmpty(file)) {
				view.addObject("flag", "F");
				view.addObject("msg", "请选择要上传的附件!");
				logger.info("请选择要上传的附件!");
				return view;
			}

			String fileFileName = file.getOriginalFilename();
			String nameEx = FileUtil.getInstance().getExtension(fileFileName);//取得文件扩展名
			//附件类型校验
			String alt = StrUtil.doNull(r.getAlloweTypes()).toUpperCase();
			if (!alt.equals("*.*")) {
				if (StrUtil.isNotEmptyWithTrim(alt) && alt.indexOf(nameEx.toUpperCase()) == -1) {
					view.addObject("flag", "F");
					view.addObject("msg", "不允许的文件类型!");
					logger.info("与实体注册允许的文件类型不匹配");
					return view;
				}
			}

			//根据objType和objId获得附件信息集合
			AttachmentStore as = new AttachmentStore();
			as.setObjType(objType);
			as.setObjId(objId);
			vo.setObj(as);
			List<AttachmentStore> asList = attachmentStoreManager.getList(vo);
			attListTotal = asList.size();

			if (attTotal <= attListTotal && attTotal > 0) {//验证附件数量
				//vinSwfUpload插件所需参数：flag,message,fileState(0:上传错误；1：上传成功)
				view.addObject("flag", "F");
				view.addObject("msg", "您上传的附件已经超过预定设置上传个数:(" + attTotal + "个)!");
				view.addObject("fileState", "0");
				logger.info("您上传的附件已经超过预定设置上传个数:(" + attTotal + "个)!");
				return view;

			} else if (attTotal < 0) {
				//return getResultMsg(request, "预定设置上传个数不能为负数!");
				view.addObject("flag", "F");
				view.addObject("msg", "预定设置上传个数不能为负数!");
				view.addObject("fileState", "0");
				logger.info("预定设置上传个数不能为负数");
				return view;
			}

			if (file.getSize() / 1024L > r.getMaxLength()) {//验证附件大小
				//return getResultMsg(request, "你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
				view.addObject("flag", "F");
				view.addObject("msg", "你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
				view.addObject("fileState", "0");
				logger.info("你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
				return view;
			}

			/*if (file.getSize() / 1024L < 10) {//验证附件大小
				//return getResultMsg(request, "你的附件小于10KB,请处理后重新上传!");
				view.addObject("flag", "F");
				view.addObject("msg", "你的附件小于10KB,请处理后重新上传!");
				view.addObject("fileState", "0");
				logger.info("你的附件小于10KB,请处理后重新上传!");
				return view;
			}*/

			String fileContentType = file.getContentType();
			logger.info(file.getName() + "  " + fileFileName + "  " + fileContentType);

			String uploadPath;//附件上传目录前段
			String downloadUrl;//附件下载地址前段

			if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {//图片
				uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/pics/";
				downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL") + "/pics/";
			} else {//文件
				uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/atta/";
				downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL") + "/atta/";
			}

			if (StrUtil.isEmptyWithTrim(uploadPath)) {
				uploadPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
			}

			//附件上传、下载目录的后段
			String cacDir = "/" + objType + "/" + new SimpleDateFormat("yyyyMM").format(new Date()) + "/" + objId + "/";
			String uplDir = uploadPath + cacDir;
			File s = new File(uplDir);
			if (!s.exists()) {
				FileUtil.getInstance().makDir(uplDir);//如果上传目录不存在，则创建
			}

			String AttachmentId = String.valueOf(System.currentTimeMillis());
			String wrFileName = cacDir + AttachmentId + "." + nameEx;
			logger.info("-----------最终文件名：" + wrFileName);
			try {
				FileUtil.getInstance().writeFile(file, uploadPath + wrFileName);
				logger.info("-----------文件上传成功：" + wrFileName);
			} catch (Exception e) {
				logger.error(">>>>>>>>>文件上传失败!!!!!!" + e);
				view.addObject("flag", "F");
				view.addObject("msg", "文件上传，发生异常");
				return view;
			}
			AttachmentStore attaStore = new AttachmentStore();
			String fileName = getFileName(fileFileName);
			attaStore.setSid(AttachmentId);
			attaStore.setObjId(objId);
			attaStore.setObjType(objType);//实体注册类型(注册英文标示)
			attaStore.setAttachmentDesc(fileName);
			attaStore.setAttachmentName(fileName);
			attaStore.setDownloadUrl(downloadUrl + cacDir);//下载地址(不包括文件名)
			attaStore.setAbsolutePath(uploadPath + cacDir);//附件绝对路径(不包括文件名)
			attaStore.setAttachmentType(nameEx);//附件类型(附件扩展名)
			String mainPicFlag = request.getParameter("mainPicFlag");
			if (Validator.isNotNull(mainPicFlag))
				attaStore.setMainPicFlag(mainPicFlag);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
			attaStore.setCreateTime(sdf.format(new Date()));
			//集成单点登录后，获得登录用户信息的方式
			String tokenId = PassportHelper.getInstance().getCurrCookie(request);

			//session中已经存在用户登录对象，则从session中获取
			Object loginObj = request.getSession().getAttribute("loginUser");
			LoginUser loginUser = null;
			if (loginObj == null) {
				loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(tokenId);
			} else {
				loginUser = PBOSSOTools.getLoginUser(request);
			}
			if (loginUser == null) {
				logger.info("AttachmentFilesAction(uploadAttachment方法)中未获取到loginUser登录信息:" + loginUser);
			}
			if (null != loginUser) {
				attaStore.setCreateUserId(loginUser.getUserId());
				attaStore.setCreateUserRealname(loginUser.getUserCname());
				attaStore.setCreateSpaceEname(loginUser.getUserEname());
				attaStore.setServerid(loginUser.getDataDomain());
			} else {
				String createUserId = request.getParameter("createUserId");
				String createUserRealname = request.getParameter("createUserRealname");
				String createSpaceEname = request.getParameter("createSpaceEname");
				if (Validator.isNotNull(createUserId))
					attaStore.setCreateUserId(createUserId);
				if (Validator.isNotNull(createUserRealname))
					attaStore.setCreateUserId(createUserRealname);
				if (Validator.isNotNull(createSpaceEname))
					attaStore.setCreateUserId(createSpaceEname);
			}

			voStore.setObj(attaStore);
			String rsid = attachmentStoreManager.saveInfo(voStore);
			if (Validator.isNull(rsid)) {
				logger.error(">>>>>>>>>上传文件信息保存数据库失败!!!!!!");
				view.addObject("flag", "F");
				view.addObject("fileState", "0");
				view.addObject("msg", "附件保存失败");
				return view;
			} else {
				if (StrUtil.isNotNull(sid)) {
					//只要历史SID不为空，就删除之前的记录
					ParamsVo voup = new ParamsVo();
					voup.setInfoId(sid);
					boolean d = attachmentStoreManager.deleteInfo(voup);
					logger.info("删除历史[sid=" + sid + "]记录:" + d);
				}
				view.addObject("flag", "T");
				view.addObject("msg", AttachmentId);//有实体记录id
				String downUrl = attaStore.getDownloadUrl().replaceAll("\\\\", "/") + attaStore.getSid() + "."
						+ attaStore.getAttachmentType();
				view.addObject("murl", downUrl);//下载地址

				logger.info("附件上传 end..........");

				return view;
			}

		}
	}

	public ResultMsg getResultMsg(HttpServletRequest request, String msg) {
		ResultMsg rmsg = new ResultMsg("F", msg);
		return rmsg;
	}

	/**
	 * 取到文件名不带后缀名
	 */
	private String getFileName(String fileName) {
		String fileFileName = "";
		if (fileName.lastIndexOf(".") > -1) {
			fileFileName = fileName.substring(0, fileName.lastIndexOf("."));
		}

		return fileFileName;
	}

	/**
	 * 跳转到列表页
	 */
	@RequestMapping("list.action")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(LIST);
		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示
		if (Validator.isNull(objId) || Validator.isNull(objType)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，系统调用异常!");
			return view;
		}
		//实体注册信息检查
		AttachmentRegister ar = new AttachmentRegister();
		ar.setRegEname(objType);
		ParamsVo vo = new ParamsVo();
		vo.setObj(ar);
		List<AttachmentRegister> arList = attachmentRegisterManager.getList(vo);
		if (arList.size() > 0) {
			ar = arList.get(0);
		}

		if (!Validator.isEmpty(ar)) {
			if ("1".equals(ar.getAttaSort().trim())) {
				view.addObject("attaSort", "1");
				view = new ModelAndView("attachment/mvc/pic-files-list");
			} else {
				view.addObject("attaSort", "0");
			}
		} else {
			view = new ModelAndView("error/error");
			view.addObject("errors", "实体未注册!");
			return view;
		}

		//集成单点登录后，获得登录用户信息的方式
		String tokenId = PassportHelper.getInstance().getCurrCookie(request);
		//session中已经存在用户登录对象，则从session中获取
		Object loginObj = request.getSession().getAttribute("loginUser");
		LoginUser loginUser = null;
		if (loginObj == null) {
			loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(tokenId);
		} else {
			loginUser = PBOSSOTools.getLoginUser(request);
		}
		if (loginUser == null) {
			this.logger.info("AttachmentFilesAction(list方法)中未获取到loginUser登录信息:" + loginUser);
		}

		AttachmentStore as = new AttachmentStore();
		as.setCreateUserId(loginUser.getUserId());
		as.setCreateUserRealname(loginUser.getUserCname());
		as.setCreateSpaceEname(loginUser.getUserEname());

		view.addObject("objId", objId);
		view.addObject("objType", objType);
		view.addObject("attrReg", ar);
		view.addObject("as", as);
		return view;
	}

	/**
	 * 图片批量上传，初始化信息，跳转到修改页面  
	 */
	@RequestMapping("edit.action")
	public ModelAndView edit(HttpServletRequest request, String id) {
		ModelAndView view = new ModelAndView(EDIT);

		AttachmentStore attaStore = null;
		ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();
		vo.setInfoId(id);
		attaStore = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
		if (Validator.isEmpty(attaStore)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "附件不存在或者已经删除！");
			return view;
		}
		view.addObject("attaStore", attaStore);
		return view;
	}

	/**
	 * description: 修改附件信息 
	 */
	@RequestMapping("updateAtta.action")
	@ResponseBody
	public ResultMsg updateAtta(HttpServletRequest request, String sid) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		if (Validator.isNull(sid)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数！");
			return rmsg;
		}

		String attachmentDesc = request.getParameter("attachmentDesc");//附件描述
		String attachmentName = request.getParameter("attachmentName");//附件名称
		String mainPicFlag = request.getParameter("mainPicFlag");//是否主图

		ParamsVo vo = new ParamsVo();
		vo.setInfoId(sid);
		AttachmentStore as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
		if (Validator.isNotNull(attachmentDesc))
			as.setAttachmentDesc(attachmentDesc);
		if (Validator.isNotNull(attachmentName))
			as.setAttachmentName(attachmentName);
		if (Validator.isNotNull(mainPicFlag))
			as.setMainPicFlag(mainPicFlag);
		vo.setInfoId(null);
		vo.setObj(as);
		boolean mark = attachmentStoreManager.editInfo(vo);
		if (!mark) {
			rmsg.setFlag("F");
			rmsg.setMsg("操作失败！");
		}

		return rmsg;
	}

	/**
	 * 设置主题
	 */
	@RequestMapping("setMainPicFlag.action")
	@ResponseBody
	public ResultMsg setMainPicFlag(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示

		if (Validator.isNull(id) || Validator.isNull(objId) || Validator.isNull(objType)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数！");
			return rmsg;
		}

		AttachmentStore as;
		ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();

		vo.setInfoId(id);
		as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);

		if (Validator.isEmpty(as)) {
			rmsg.setFlag("F");
			rmsg.setMsg("图片不存在或者已经删除！");
			return rmsg;
		}

		LoggerVo loggerVo = new LoggerVo();
		vo = this.getParamsVo(request);

		AttachmentStore asp = new AttachmentStore();
		asp.setObjType(objType);
		asp.setObjId(objId);
		vo.setInfoId(null);
		vo.setObj(asp);
		List<AttachmentStore> asList = attachmentStoreManager.getList(vo);
		for (int i = 0; i < asList.size(); i++) {
			if (id.trim().equals(asList.get(i).getSid().trim())) {
				asList.get(i).setMainPicFlag("1");
			} else {
				asList.get(i).setMainPicFlag("0");
			}
			vo.setObj(asList.get(i));
			boolean edrs = attachmentStoreManager.editInfo(vo);
			if (!edrs) {
				rmsg.setFlag("F");
				rmsg.setMsg("操作失败！");
				return rmsg;
			}
		}

		return rmsg;
	}

	@RequestMapping("downloadAttachment.action")
	public @ResponseBody
	ResultMsg downloadAttachment(HttpServletRequest request, HttpServletResponse response, String sid) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		if (Validator.isNull(sid)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数!");
			return rmsg;
		}

		//校验附件是否存在
		ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();
		vo.setInfoId(sid);
		AttachmentStore as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
		if (Validator.isEmpty(as)) {
			rmsg.setFlag("F");
			rmsg.setMsg("附件不存在或者已经删除!");
			return rmsg;
		}

		String attafileName = as.getSid() + "." + as.getAttachmentType();
		String uploadDirpro = this.getUploadDir(request, sid, as) + attafileName;

		File file = new File(uploadDirpro);
		try {
			request.setCharacterEncoding("UTF-8");
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			long fileLength = file.length();//文件长度
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(attafileName.getBytes("utf-8"), "ISO8859-1"));
			//设置输出长度
			response.setHeader("Content-Length", String.valueOf(fileLength));
			//获取输入流
			bis = new BufferedInputStream(new FileInputStream(uploadDirpro));
			//输出流
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			//关闭流
			bis.close();
			bos.close();
		} catch (UnsupportedEncodingException e) {
			rmsg.setFlag("F");
			rmsg.setMsg("不支持的编码!");
			return rmsg;

		} catch (FileNotFoundException e) {
			rmsg.setFlag("F");
			rmsg.setMsg("未找到附件!");
			return rmsg;

		} catch (IOException e) {
			rmsg.setFlag("F");
			rmsg.setMsg("操作失败!");
			return rmsg;

		}

		return null;
	}

	/**
	 * 访问ip验证
	 */
	private boolean checkIp(String userIp, String defineIp) {
		String uIp = StrUtil.doNull(userIp);
		String defIp = StrUtil.doNull(defineIp);
		if (StrUtil.isEmptyWithTrim(defIp)) {
			return true;
		}
		if (defIp.indexOf(uIp) != -1) {
			return true;
		}
		return false;
	}

	/**
	 * 查询列表数据
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("list!data.action")
	protected @ResponseBody
	Object data(HttpServletRequest request, String page, String rows) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		String objType = request.getParameter("objType");
		String objId = request.getParameter("objId");

		if (Validator.isNull(objType) || Validator.isNull(objId)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数！");
			return rmsg;
		}

		AttachmentRegister attrReg = this.getAttaRegister(objType, attachmentRegisterManager);
		if (Validator.isEmpty(attrReg)) {
			rmsg.setFlag("F");
			rmsg.setMsg("实体未注册!");
			return rmsg;
		}

		//权限检查
		String ip = StrUtil.doNull(attrReg.getIpAddress());
		if (StrUtil.isNotEmptyWithTrim(ip)) {
			boolean ipflag = checkIp(request.getRemoteAddr(), attrReg.getIpAddress());
			if (!ipflag) {
				rmsg.setFlag("F");
				rmsg.setMsg("无访问权限！");
				return rmsg;
			}
		}

		ParamsVo vo = new ParamsVo();
		AttachmentStore as = new AttachmentStore();
		as.setObjId(objId);
		as.setObjType(objType);
		vo.setObj(as);

		List<AttachmentStore> asList = attachmentStoreManager.getList(vo);
		if ("1".equals(attrReg.getAttaSort().trim())) {
			Map<String, Object> mapData = new HashMap<String, Object>();
			mapData.put("flag", "T");
			mapData.put("msg", asList);
			return mapData;
		} else {
			return asList;
		}

	}

	//获得附件库注册信息
	public AttachmentRegister getAttaRegister(String objType, AttachmentRegisterManager attachmentRegisterManager) {
		AttachmentRegister attrReg = new AttachmentRegister();
		attrReg.setRegEname(objType);
		ParamsVo vo = new ParamsVo();
		vo.setObj(attrReg);
		List<AttachmentRegister> arList = attachmentRegisterManager.getList(vo);
		if (arList.size() > 0) {
			attrReg = arList.get(0);
			return attrReg;
		}
		return null;
	}

	/**
	 * description:获得上传目录  
	 * @author mhguo 
	 * @update 2015-5-28
	 */
	public String getUploadDir(HttpServletRequest request, String id, AttachmentStore as) {
		String uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY");
		String downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL");
		if (StrUtil.isEmptyWithTrim(uploadPath)) {
			uploadPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
		}
		//java中使用正则获得路径
		String regEx = downloadUrl;
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(as.getDownloadUrl());
		String filePath_ = mat.replaceAll("");
		String attaFilePath = filePath_.substring(1, filePath_.lastIndexOf("/"));
		String uploadDir = uploadPath + File.separator + attaFilePath + File.separator;
		return uploadDir;
	}

	/**
	 * 单个删除
	 */
	@RequestMapping("deleteAtta")
	@ResponseBody
	public ResultMsg delete(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功");

		String objType = request.getParameter("objType");
		String objId = request.getParameter("objId");

		if (Validator.isNull(id) || Validator.isNull(objType) || Validator.isNull(objId)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数！");
			return rmsg;
		}

		//校验附件是否存在
		ParamsVo vo = new ParamsVo();
		vo.setInfoId(id);
		AttachmentStore as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
		if (Validator.isEmpty(as)) {
			rmsg.setFlag("F");
			rmsg.setMsg("附件不存在或者已经删除！");
			return rmsg;
		}
		String attafileName = as.getSid() + "." + as.getAttachmentType();
		String uploadDir = getUploadDir(request, id, as);
		String uploadDirpro = uploadDir + attafileName;

		//得到实体注册信息
		AttachmentRegister ar = this.getAttaRegister(objType, attachmentRegisterManager);

		if (!Validator.isEmpty(ar)) {
			if ("1".equals(ar.getAttaSort().trim())) {
				String wrMiddleFileName = as.getSid() + ".m." + as.getAttachmentType();
				logger.info("wrMiddleFileName[{}]" + wrMiddleFileName);
				String uploadDirm = uploadDir + wrMiddleFileName;
				String wrSmallFileName = as.getSid() + ".s." + as.getAttachmentType();
				logger.info("wrSmallFileName[{}]" + wrSmallFileName);
				String uploadDirs = uploadDir + wrSmallFileName;

				File file = new File(uploadDirpro);
				File filem = new File(uploadDirm);
				File files = new File(uploadDirs);

				if (file.exists() && filem.exists() && files.exists()) {
					boolean ob = file.delete();
					boolean obm = filem.delete();
					boolean obs = files.delete();
					if (ob & obm && obs) {
						rmsg.setFlag("T");
						rmsg.setMsg("操作成功！");
					} else {
						rmsg.setFlag("F");
						rmsg.setMsg("操作失败！");
						return rmsg;
					}
				} else {
					rmsg.setFlag("T");
					//rmsg.setMsg("图片信息已删除，但没有找到图片！");
					rmsg.setMsg("图片信息已删除！");
				}
			} else {
				File file = new File(uploadDirpro);
				if (file.exists()) {
					boolean ob = file.delete();
					if (ob) {
						rmsg.setFlag("T");
						rmsg.setMsg("操作成功！");
					} else {
						rmsg.setFlag("F");
						rmsg.setMsg("操作失败！");
						return rmsg;
					}
				} else {
					rmsg.setFlag("T");
					//rmsg.setMsg("附件信息已删除，但没有找到附件！");
					rmsg.setMsg("附件信息已删除！");
				}
			}
		} else {
			rmsg.setFlag("F");
			rmsg.setMsg("实体未注册!");
			return rmsg;
		}

		vo.setInfoId(id);
		boolean mark = attachmentStoreManager.deleteInfo(vo);
		if (!mark) {
			rmsg.setFlag("F");
			rmsg.setMsg("操作失败！");
			return rmsg;
		}

		return rmsg;
	}

	/**
	 * 批量删除
	 */
	@RequestMapping("deleteAttas")
	@ResponseBody
	public ResultMsg deletes(HttpServletRequest request, String ids) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功");

		if (Validator.isNull(ids)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数！");
			return rmsg;
		}

		//校验附件是否存在
		ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();
		AttachmentStore as;
		String idsArr[] = ids.split(",");
		for (int i = 0; i < idsArr.length; i++) {
			vo.setInfoId(idsArr[i]);
			as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
			if (Validator.isEmpty(as)) {
				rmsg.setFlag("F");
				rmsg.setMsg("附件不存在或者已经删除！");
				continue;
			}
			this.delete(request, idsArr[i]);
		}
		return rmsg;
	}

	/**
	 */
	@Override
	protected BaseManager getBaseManager() {
		return null;
	}

	/**
	 */
	@Override
	protected String getPrefix() {
		return "attachment/mvc/attachment-files-";
	}

}
